import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/pages/general/AccountDeletionConfirmation.dart';
import 'package:word_range_client/pojo/vo/UserVo.dart';
import 'package:word_range_client/viewModels/UserViewModel.dart';

import '../../pojo/dto/UserDto.dart';
import '../../widgets/general/Toastification.dart';

class AccountEdit extends StatefulWidget {
  const AccountEdit({super.key});

  @override
  State<AccountEdit> createState() => _AccountEditState();
}

class _AccountEditState extends State<AccountEdit> {

  TextEditingController _nameController = TextEditingController();
  TextEditingController _signatureController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadLocalAccountData();
  }

  void _loadLocalAccountData() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString("currentUser");
    if (userJson != null) {
      setState(() {
        UserVo user = UserVo.fromJson(json.decode(userJson));
        _nameController.text = user.name!;
        _signatureController.text = user.signature!;
      });
    }
  }

  void _apply(){
    if (_nameController.text.isEmpty) {
      Toastification toastification = Toastification(context: context);
      toastification.showWarning("昵称不得为空");
    }
    UserDto userDto = UserDto(
        name: _nameController.text,
        signature: _signatureController.text
    );
    UserViewModel userViewModel = UserViewModel();
    userViewModel.updateUser(userDto).then((value) {
      if (value.code == 1) {
        Toastification toastification = Toastification(context: context);
        toastification.showSuccess("修改成功");
        Navigator.pop(context);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("编辑账户资料"),
        backgroundColor: Theme.of(context).colorScheme.primary,
        actions: const [_DeletionConfirmationButton()],
      ),
      body:
      _AccountEditBody(
        nameController: _nameController,
        signatureController: _signatureController,
      ),
      floatingActionButton: _ApplyButton(onPressed: _apply,),
    );
  }
}

class _AccountEditBody extends StatefulWidget {
  const _AccountEditBody({super.key, required this.nameController, required this.signatureController});

  final TextEditingController nameController;
  final TextEditingController signatureController;

  @override
  State<_AccountEditBody> createState() => _AccountEditBodyState();
}

class _AccountEditBodyState extends State<_AccountEditBody> {

  UserVo user = UserVo();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _loadLocalAccountData();
  }

  Future<void> _loadLocalAccountData() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString("currentUser");
    if (userJson != null) {
      setState(() {
        user = UserVo.fromJson(json.decode(userJson));
      });
    }
  }

  Widget _initImage(){
    return user.avatarUrl == "" || user.avatarUrl == null ?
    Hero(
        tag: "avatarImg",
        child: Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 10,
                spreadRadius: 3,
                offset: const Offset(0, 4),
              )
            ],
          ),
          child: const CircleAvatar(
            radius: 90,
            backgroundImage: AssetImage("assets/images/Default_head.png"),
          ),
        )
    ):
    Hero(
        tag: "avatarImg",
        child: Container(
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.3),
                blurRadius: 10,
                spreadRadius: 3,
                offset: const Offset(0, 4),
              )
            ],
          ),
          child: CircleAvatar(
            radius: 90,
            backgroundImage: NetworkImage(user.avatarUrl!),
          ),
        )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: const EdgeInsets.all(10),
        color: Theme.of(context).colorScheme.primary,
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(maxWidth: 800),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              const SizedBox(),
              _initImage(),
              SizedBox(
                  height: 270,
                  child: ListView(
                    children:  [
                      _EditCard(
                          nameController: widget.nameController,
                          signatureController: widget.signatureController
                      ),
                    ],
                  )
              ),
              const SizedBox(),
              const SizedBox(),
            ],
          ),
        )
      )
    );
  }
}

class _EditCard extends StatelessWidget {
  const _EditCard({super.key, required this.nameController, required this.signatureController});

  final TextEditingController nameController;
  final TextEditingController signatureController;


  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 6,
      child: Padding(
          padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 10,),
            const Text(
                "昵称",
                style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                )
            ),
            const SizedBox(height: 10,),
            TextField(
              controller: nameController,
              decoration: InputDecoration(
                hintText: "请输入昵称",
                hintStyle: const TextStyle(
                  color: Colors.grey,
                ),
                fillColor: Colors.white,
                filled: true,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            ),
            const SizedBox(height: 10,),
            const Text(
                "个性签名",
                style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w500,
                )
            ),
            const SizedBox(height: 10,),
            TextField(
              controller: signatureController,
              decoration: InputDecoration(
                hintText: "留下你的个性签名吧",
                hintStyle: const TextStyle(
                  color: Colors.grey,
                ),
                fillColor: Colors.white,
                filled: true,
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                ),
              ),
            )

          ],
        ),
      )
    );
  }
}

class _DeletionConfirmationButton extends StatefulWidget {
  const _DeletionConfirmationButton({super.key});

  @override
  State<_DeletionConfirmationButton> createState() => _DeletionConfirmationButtonState();
}

class _DeletionConfirmationButtonState extends State<_DeletionConfirmationButton> {
  void _toAccountDeletionConfirmationPage(){
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const AccountDeletionConfirmation(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: _toAccountDeletionConfirmationPage,
      icon: Hero(
          tag: "AccountDeletionConfirmation",
          child: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              // 圆角
              borderRadius: BorderRadius.circular(10),
              color: Theme.of(context).colorScheme.error,
            ),
            child: const Icon(
              Icons.delete_forever,
              color: Colors.white,
            ),
          )
      ),
    );
  }
}

class _ApplyButton extends StatefulWidget {
  const _ApplyButton({super.key, this.onPressed});

  final VoidCallback? onPressed;

  @override
  State<_ApplyButton> createState() => _ApplyButtonState();
}

class _ApplyButtonState extends State<_ApplyButton> {
  @override
  Widget build(BuildContext context) {
    return  FloatingActionButton(
      onPressed: widget.onPressed,
      backgroundColor: Colors.white,
      child: const Icon(Icons.check),
    );
  }
}


